use crate::models::catalog_translations::{self, CreateCatalogTranslationParams};
use axum::{
    Json, Router,
    extract::State,
    routing::{get, post},
};
use loco_rs::prelude::*;

pub fn routes() -> Router<AppContext> {
    Router::new()
        .route("/catalog-translations", post(create))
        .route("/catalog-translations/:id", get(get_by_id))
        .route("/catalog-translations/:id/delete", post(delete))
        .route(
            "/catalog-translations/by-catalog/:catalog_id",
            get(get_by_catalog),
        )
        .route(
            "/catalog-translations/by-catalog-and-locale/:catalog_id/:locale",
            get(get_by_catalog_and_locale),
        )
}

async fn create(
    State(state): State<AppContext>,
    Json(params): Json<CreateCatalogTranslationParams>,
) -> Result<Response> {
    let catalog_translation = catalog_translations::Model::create(&state.db, &params).await?;
    format::json(catalog_translation)
}

async fn get_by_id(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    let catalog_translation = catalog_translations::Model::find_by_id(&state.db, &id).await?;
    format::json(catalog_translation)
}

async fn delete(
    State(state): State<AppContext>,
    axum::extract::Path(id): Path<String>,
) -> Result<Response> {
    let catalog_translation = catalog_translations::Model::find_by_id(&state.db, &id).await?;
    catalog_translation.delete(&state.db).await?;
    format::json(())
}

async fn get_by_catalog(
    State(state): State<AppContext>,
    axum::extract::Path(catalog_id): Path<String>,
) -> Result<Response> {
    let catalog_translations =
        catalog_translations::Model::find_by_catalog_id(&state.db, &catalog_id).await?;
    format::json(catalog_translations)
}

async fn get_by_catalog_and_locale(
    State(state): State<AppContext>,
    Path((catalog_id, locale)): Path<(String, String)>,
) -> Result<Response> {
    let catalog_translation =
        catalog_translations::Model::find_by_catalog_id_and_locale(&state.db, &catalog_id, &locale)
            .await?;
    format::json(catalog_translation)
}
